﻿using blackhouse.NemoBlog.Business;
using blackhouse.NemoBlog.Business.Presenter;
using blackhouse.NemoBlog.Business.View;
using mojoPortal.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace blackhouse.NemoBlog.Web {
    public partial class NemoBlogPostPage : NonCmsBasePage {

        #region Fields

        private IPostView view;
        private PostPresenter presenter;
        private NemoBlogPost post;
        private NemoBlogSettings settings;

        #endregion

        #region Methods

        protected override void CreateChildControls() {
            base.CreateChildControls();

            this.post = new NemoBlogPost(this.GetPostId());
            if (!post.Exists) return;

            this.settings = new NemoBlogSettings(post.ModuleId);
            IBlogViewFactory viewFactory = settings.Configuration.GetViewFactory();
            this.view = null;
            if (viewFactory != null)
                this.view = viewFactory.LoadPostView();
            Control viewControl = view as Control;
            if (this.view == null || viewControl == null) {
                viewControl = this.LoadControl("~/StandardNemoBlogPost.ascx");
                this.view = viewControl as IPostView;
            }
            viewControl.Init += viewControl_Init;
            viewControl.Load += viewControl_Load;
            this.pnlPostWrapper.Controls.Add(viewControl);
        }

        void viewControl_Load(object sender, EventArgs e) {
            base.OnLoad(e);

            if (!this.post.Exists) return;
            this.presenter = new PostPresenter(this.view, this.settings.Configuration.GetPostModel(this.post.PostId));
            this.presenter.Load();
            this.presenter.AttachEvents();
        }

        void viewControl_Init(object sender, EventArgs e) {
            this.EnsureChildControls();
            this.view.PostId = this.GetPostId();
        }

        private int GetPostId() {
            int postId = 0;
            Int32.TryParse(Request["post"], out postId);
            return postId;
        }

        #endregion

    }
}